<?php
namespace App\Utility;
class Tree
{
	function list_to_tree($list, $pk='id', $pid = 'pid', $child = 'children', $root = 0) {
		// 创建Tree
		$tree = array();
		if(is_array($list)) {
			// 创建基于主键的数组引用
			$refer = array();
			foreach ($list as $key => $data) {
				$refer[$data[$pk]] =& $list[$key];
			}
			foreach ($list as $key => $data) {
				// 判断是否存在parent
				$parentId =  $data[$pid];
				if ($root == $parentId) {
					$tree[] =& $list[$key];
				}else{
					if (isset($refer[$parentId])) {
						$parent =& $refer[$parentId];
						$parent[$child][] =& $list[$key];
					}
				}
			}
		}
		return $tree;
	}
	//传递一个父级分类ID返回所有子级分类
	public function getChildsId($cate, $id) {

        $arr = array();
    	foreach ($cate as $v) {
        	if ($v['pid'] == $id) {
        		$arr[] = $v['id'];
        		$arr = array_merge($arr,$this->getChildsId($cate, $v['id']));
        	}
    	}
    	return $arr;
    }
	
	//传递一个子分类ID返回父级分类--用于面包屑导航等
    Public function getParents($cate, $id,$id_key='id',$pid_key='pid'){
		
        $arr = array();
        foreach ($cate as $v){
            if (($v[$id_key] == $id)) {
				$arr[] = $v;				
                $arr = array_merge($arr,$this->getParents($cate, $v[$pid_key],$id_key,$pid_key));				
            }
        }
        return $arr;
    }
}